package Demo1;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;


@WebServlet({"/test/cookie","/sendcookie"})
public class CookieTest extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         String path = req.getServletPath();
         if("/test/cookie".equals(path)){
             doCookie(req,resp);
         }else if("/sendcookie".equals(path)){
             doReceive(req,resp);
         }
    }

    /**
     * 打印浏览器发送的cookie
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void doReceive(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException{
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            String value = cookie.getValue();
            System.out.println(name+"="+value);
            out.print(name+"="+value);
        }
    }

    private void doCookie(HttpServletRequest req, HttpServletResponse resp) throws IOException,ServletException{
        // 创建cookie
        Cookie cookie = new Cookie("username","jack");
        Cookie cookie2 = new Cookie("password","123456");

        // 设置有效时间
        cookie.setMaxAge(-1);
        cookie2.setMaxAge(-1);

        //  为 cookie设置url
        cookie.setPath(req.getContextPath());
        cookie2.setPath(req.getContextPath());

        //给浏览器返回cookie
        resp.addCookie(cookie);
        resp.addCookie(cookie2);
    }
}
